package com.gitee.dolt.utils.web;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.gitee.dolt.utils.json.HutoolGlobalJsonConfig;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;

/**
 * @author LYH
 */
public class ResponseUtils {

    public static void renderJson(HttpServletResponse response, int status, Object data) {
        response.setStatus(status);
        JSON json = JSONUtil.parse(data, HutoolGlobalJsonConfig.INSTANCE.getConfig());
        String str = JSONUtil.toJsonStr(json);
        ServletUtil.write(response, str, ContentType.build(ContentType.JSON.toString(), CharsetUtil.charset(CharsetUtil.UTF_8)));
    }

    public static void renderJson(HttpServletResponse response, Object data) {
        renderJson(response, HttpStatus.HTTP_OK, data);
    }

    public static void renderString(HttpServletResponse response, String data) {
        ServletUtil.write(response, data, ContentType.build(ContentType.JSON.toString(), CharsetUtil.charset(CharsetUtil.UTF_8)));
    }

    public static void renderFile(HttpServletResponse response, File file) {
        renderFile(response, file, file.getName());
    }

    public static void renderFile(HttpServletResponse response, File file, String fileName) {
        String contentType = ObjectUtil.defaultIfNull(FileUtil.getMimeType(fileName), "application/octet-stream");
        BufferedInputStream in = null;
        try {
            in = FileUtil.getInputStream(file);
            ServletUtil.write(response, in, contentType, fileName);
        } finally {
            IoUtil.close(in);
        }
    }
}
